﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DrawManage.Tools;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Web.Script.Serialization;

namespace DrawManage.Controllers
{
    public class ApiController : Controller
    {
        // GET: Api
        BaseDao dao = new BaseDao();
        public ActionResult Index()
        {
            return View();
        }


        //增加根节点
        public ActionResult AddNodeRoot()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                map["DrawNum"] = GetSortNum("0");
                dao.save("Node", map);

                result.Add("result", "OK");
                string TreeObjStr = zTree.RebuildTree();
                result.Add("TreeObjStr", TreeObjStr);

                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        //增加子节点
        public ActionResult AddNodeChildren()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                //map.Add("IsParent", "1");
                map["DrawNum"] = GetSortNum(map["ParentId"].ToString());

                dao.save("Node", map);
                string ParentId = map["ParentId"].ToString();
                string DrawNum = map["DrawNum"].ToString();
                string NodeName = map["NodeName"].ToString();


                result.Add("result", "OK");
                result.Add("ParentId", ParentId);
                result.Add("DrawNum", DrawNum);
                result.Add("NodeName", NodeName);
                string Id;
                Id = dao.GetString("Node", "Id", "and ParentId=" + ParentId + " and DrawNum=" + DrawNum);
                result.Add("Id", Id);

                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        

        //查找当前排序，获取新增排序序号
        private string GetSortNum(string ParentId)
        {
            int num = 0;
            string sql = "select Count(*) as Num from Node where ParentId=" + ParentId;
            string SqlNum = dao.GetList(sql, new string[] { "Num" })[0]["Num"].ToString();
            num = int.Parse(SqlNum) + 1;
            return num.ToString();
        }

        //更新节点号
        public ActionResult UpdateNode()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                //map.Add("IsParent", "1");
                string Id = map["Id"].ToString();
                map.Remove("Id");

                dao.update("Node", map, "Id=" + Id);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        //根据节点数据 逆向获取整个树编号
        public ActionResult GetAllTreeByNode()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();
                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }

                string Id = map["Id"].ToString();
                string sql = ";with hgo as" +       //数据库逆向递归 默认最大迭代100次
                    " (" +
                    "  select *,1 as rank from Node where Id=" + Id +
                    " union all" +
                    " select h.*,h1.rank+1 from Node h join hgo h1 on h.Id=h1.ParentId" +
                    " )" +
                    " select * from hgo ORDER BY rank desc";
                var list = dao.GetList(sql, new string[] { "NodeName", "DrawNum" });
                string NodeNameSerial = "-";
                string DrawNumSerial = "-";
                for (int i = 0; i < list.Count; i++)
                {
                    NodeNameSerial += list[i]["NodeName"].ToString() + "-";
                    DrawNumSerial += list[i]["DrawNum"].ToString() + "-";
                }

                result.Add("result", "OK");
                result.Add("NodeNameSerial", NodeNameSerial);
                result.Add("DrawNumSerial", DrawNumSerial);

                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        public ActionResult PassWordChange()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            if (Request.Cookies["id"] == null || Request.Cookies["id"].ToString() == "")
            {
                Response.Cookies["id"].Value = "";
                Response.Cookies["id"].Expires = DateTime.Now.AddDays(-1);
                result.Add("result", "error");
            }

            string Id = Request.Cookies["id"].Value;
            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                //查找当前用户
                string sql = "select count(Id) as num from t_d_User where PassWord='" + map["OldPass"].ToString() + "'" +
                    " and Id="+Id;
                Dictionary<string, object> UserMap = dao.GetList(sql, new string[] { "num" })[0];
                if (UserMap["num"].ToString() != "1")
                {
                    result.Add("result", "原始密码错误");
                    return Json(result);
                }

                if (map["NewPass"].ToString() != map["ComfirPass"].ToString())
                {
                    result.Add("result", "两次密码不一致");
                    return Json(result);
                }
                string PassWord = map["NewPass"].ToString();
                map.Clear();
                map.Add("PassWord", PassWord);
                dao.update("t_d_User", map, "Id=" + Id);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }

        public ActionResult UserAdd()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                map["IsDelete"] = "0";
                map["PassWord"] = "123456";
                string UserName = map["UserName"].ToString();
                
                UserName = UserName.Trim();
                //查找当前用户
                string sql = "select count(Id) as num from t_d_User where UserName='" + UserName + "'";
                Dictionary<string, object> UserMap = dao.GetList(sql, new string[] { "num" })[0];
                if (UserMap["num"].ToString() != "0")
                {
                    result.Add("result", "该用户已经存在");
                    return Json(result);
                }

                dao.save("t_d_User", map);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }


        }


        public ActionResult UserDel()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }

                string Id = map["Id"].ToString();
                map["IsDelete"] = "1";
                map.Remove("Id");
                dao.update("t_d_User", map,"Id="+Id);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }




        [HttpPost]
        public ActionResult UserTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();

            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,Id,UserName,role" +
                        "" +
                        " FROM t_d_user " +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "Id", "UserName", "role" });
                SqlNum = "select count(Id) as TotalNum FROM t_d_user where 1=1 " + condition;
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /UserController/UserTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }

        }


        public ActionResult GetDrawTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();

            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,a.Id,a.UserId,a.SerialDrawName,a.SerialDrawNum," +
                        " CONVERT(varchar(100), a.GetTime, 120) as GetTime,a.IncreaseNum,a.MotorId,a.Memo,a.Type,b.UserName" +
                        " FROM t_d_DrawDetail a inner join t_d_User b on a.UserId=b.Id" +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "Id", "UserId", "SerialDrawName", "SerialDrawNum", "MotorId", "GetTime", "IncreaseNum", "UserName", "Memo", "Type" });
                SqlNum = "select count(a.Id) as TotalNum FROM t_d_DrawDetail a inner join t_d_User b on a.UserId=b.Id where 1=1 " + condition;
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /UserController/UserTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }


        }


        public ActionResult Api_GetDrawNumIncrease()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();
            if (Request.Cookies["id"] == null || Request.Cookies["id"].ToString() == "")
            {
                Response.Cookies["id"].Value = "";
                Response.Cookies["id"].Expires = DateTime.Now.AddDays(-1);
                result.Add("result", "error");
            }
            string UserId = Request.Cookies["id"].Value;

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();
                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }

                string Id = map["Id"].ToString();
                string sql = ";with hgo as" +       //数据库逆向递归 默认最大迭代100次
                    " (" +
                    "  select *,1 as rank from Node where Id=" + Id +
                    " union all" +
                    " select h.*,h1.rank+1 from Node h join hgo h1 on h.Id=h1.ParentId" +
                    " )" +
                    " select * from hgo ORDER BY rank desc";
                var list = dao.GetList(sql, new string[] { "NodeName", "DrawNum" });
                string NodeNameSerial = "";
                string SerialDrawNum = "";
                if (list.Count<3)
                {
                    result.Add("result", "请选择至少有3级:");
                    return Json(result);
                }

                for (int i = 0; i < list.Count; i++)
                {
                    NodeNameSerial = list[i]["NodeName"].ToString();
                    SerialDrawNum += list[i]["DrawNum"].ToString();
                    
                }

                //寻找当前编号并自增
                sql = "select Count(Id) as num from t_d_DrawDetail where IsDelete=0 and UserId=" + UserId + " and SerialDrawNum='" + SerialDrawNum + "'";
                var map2 = dao.GetList(sql, new string[] { "num" })[0];
                int IncreaseNum = 1 + int.Parse(map2["num"].ToString());

                //保存获取编号
                string TempTime = DateTime.Now.ToString();
                Dictionary<string, object> Map3 = new Dictionary<string, object>()
                {
                    ["SerialDrawName"] = NodeNameSerial,
                    ["SerialDrawNum"] = SerialDrawNum,
                    ["MotorId"] = map["MotorId"].ToString(),
                    ["UserId"] = UserId,
                    ["IncreaseNum"] = IncreaseNum.ToString().PadLeft(3,'0'),
                    ["GetTime"]= TempTime,
                    ["Memo"]=map["Memo"].ToString(),
                    ["Type"]=map["Type"].ToString(),
                    ["IsDelete"]=0,
                };
                dao.save("t_d_DrawDetail", Map3);

                //获取到新增数据的编号
                if("组件"== map["Type"].ToString())
                {
                    string DrawDetailId= dao.GetString("t_d_DrawDetail", "Id", "and GetTime='" + TempTime + "'");
                    Dictionary<string, object> Map4 = new Dictionary<string, object>()
                    {
                        ["DrawDetailId"]= DrawDetailId,
                        ["SerialDrawName"] = NodeNameSerial,
                        ["SerialDrawNum"] = SerialDrawNum,
                        ["MotorId"] = map["MotorId"].ToString(),
                        ["ParentId"]=0


                    };
                }


                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        public ActionResult GetDrawNumDel()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }

                string Id = map["Id"].ToString();
                map["IsDelete"] = "1";
                map.Remove("Id");
                dao.update("t_d_DrawDetail", map, "Id=" + Id);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }

        }

        public ActionResult AddRootDrawCombo()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();
            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();
                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                map.Add("ComboId", DateTime.Now.ToString("yyyyMMddHHmmss"));
                dao.save("t_d_DrawCombo", map);
                result.Add("result", "OK");
                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }



        }


        public ActionResult DrawComboTableRequest()
        {

            int page = Int32.Parse(Request.Form["page"]);
            int limit = Int32.Parse(Request.Form["limit"]);
            string condition = Request.Form["condition"].ToString();
            string SortName = Request.Form["SortName"].ToString();
            string Order = Request.Form["Order"].ToString();

            try
            {
                //以下是分页查询语句
                string sql = "", SqlNum = "";
                sql = " select top " + limit.ToString() + " * from " +
                        " ( " +
                        " SELECT ROW_NUMBER() OVER (order by " + SortName + " " + Order + ") as rowNumber,a.Id,a.DrawDetailId,a.ParentId,a.SerialDrawName,a.SerialDrawNum," +
                        " a.IncreaseNum,a.MotorId,a.ComboId" +
                        " FROM t_d_DrawCombo a " +
                        " where 1=1 " + condition +
                        " ) as s " +
                        " where rowNumber>" + (limit * (page - 1)).ToString();

                List<Dictionary<string, object>> list = new List<Dictionary<string, object>>();
                list = dao.GetList(sql, new string[] { "Id", "DrawDetailId", "ParentId", "SerialDrawName", "SerialDrawNum", "MotorId", "IncreaseNum", "ComboId" });
                SqlNum = "select count(a.Id) as TotalNum FROM t_d_DrawCombo a where 1=1 " + condition;
                List<Dictionary<string, object>> ListNum = new List<Dictionary<string, object>>();
                ListNum = dao.GetList(SqlNum, new string[] { "TotalNum" });

                TableData td = new TableData();
                td.code = "";
                td.msg = "";
                td.count = int.Parse(ListNum[0]["TotalNum"].ToString());
                td.data = list;
                return Json(td);
            }
            catch (Exception ex)
            {
                Dictionary<string, object> datalog = new Dictionary<string, object>();
                datalog.Add("type", int.Parse("1"));
                datalog.Add("OpTime", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                datalog.Add("OpID", int.Parse("1"));
                datalog.Add("OpLog", "异常：加载需求管理表格异常 /UserController/UserTableRequest:" + ex.Message.ToString().Replace("'", ""));
                dao.save("T_LOG", datalog);
                return Json('0');
            }


        }


        public ActionResult LoadTree_DrawCombo()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                string ComboId = map["ComboId"].ToString();

                result.Add("result", "OK");
                string TreeObjStr = zTree.RebuildTree_DrawCombo(ComboId);
                result.Add("TreeObjStr", TreeObjStr);

                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }
        }


        public ActionResult AddDrawComboByDraw()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                //首先搜索出对应的ComboId
                string sql = "select * from t_d_DrawCombo where IsDelete=0 and ComboId='" + map["ComboId"].ToString() + "'";
                var AllList = dao.GetList(sql, new string[] { "Id", "DrawDetailId", "ParentId", "SerialDrawName", "SerialDrawNum", "MotorId", "IncreaseNum", "ComboId" });
                var Nodes = AllList.FindAll(t => t["ParentId"].ToString() == map["ParentId"].ToString());
                int InstallNum = Nodes.Count;
                InstallNum += 1;
                map.Add("InstallNum", InstallNum);
                map.Add("IsDelete", 0);
                dao.save("t_d_DrawCombo", map);

                string ComboId = map["ComboId"].ToString();
                string TreeObjStr = zTree.RebuildTree_DrawCombo(ComboId);
                result.Add("TreeObjStr", TreeObjStr);

                result.Add("result", "OK");

                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }


        }

        public ActionResult DelDrawCombo()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                string Id = map["Id"].ToString();
                map.Clear();
                map.Add("IsDelete", 1);

                dao.update("t_d_DrawCombo", map, "Id=" + Id);
                dao.update("t_d_DrawCombo", map, "ParentId=" + Id);

                result.Add("result", "OK");

                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }


        }



        public ActionResult AddNodeByCombo()
        {
            var sr = new StreamReader(Request.InputStream);
            var stream = sr.ReadToEnd();
            JObject obj = JObject.Parse(stream);
            sr.Close();
            Dictionary<string, object> result = new Dictionary<string, object>();

            try
            {
                Dictionary<string, object> map = new Dictionary<string, object>();

                foreach (var item in obj)
                {
                    map.Add(item.Key, item.Value);
                }
                string TCurr_Id = map["ParentId"].ToString();       //需要挂载的父节点Id
                string TCurr_ComboId = map["ParentComboId"].ToString(); //需要挂载的父树标识

                string ComboId = map["ComboId"].ToString();         //当前组合的ComboId
                string Id = map["ComboRootId"].ToString();

                //下面分步进行挂接
                //把当前组合的数据全部找出来,插入数据库，获取新的自增数据
                string sql = "select * from t_d_DrawCombo where IsDelete=0 and ComboId='" + ComboId + "'";
                var List1 = dao.GetList(sql, new string[] { "Id","DrawDetailId", "ParentId", "SerialDrawName", "MotorId", "ComboId", "IsDelete", "IncreaseNum", "SerialDrawNum", "InstallNum" });
                for (int i = 0; i < List1.Count; i++)
                {
                    List1[i].Add("NewId", "");
                    sql = "insert into t_d_DrawCombo (DrawDetailId, ParentId, SerialDrawName, MotorId, ComboId, IsDelete,IncreaseNum, SerialDrawNum, InstallNum) OutPut inserted.Id as NewId values(" +
                        "'"+List1[i]["DrawDetailId"] +"','" + List1[i]["ParentId"] + "','"  + List1[i]["SerialDrawName"] + "','" + List1[i]["MotorId"] + "','" + TCurr_ComboId + "','"
                         + List1[i]["IsDelete"] + "','" + List1[i]["IncreaseNum"] + "','" + List1[i]["SerialDrawNum"] + "','" + List1[i]["InstallNum"] + "')";
                    List1[i]["NewId"] = dao.GetList(sql, new string[] { "NewId" })[0]["NewId"].ToString();
                }
                //Update所有已知的数据使得正确挂载节点
                string tempParentId = "";
                string tempNewId = "";
                for (int i = 0; i < List1.Count; i++)
                {
                    if (List1[i]["ParentId"].ToString()=="0")
                    {
                        sql = "update t_d_DrawCombo set ParentId=" + TCurr_Id + " where Id=" + List1[i]["NewId"].ToString();
                    }
                    else
                    {

                        tempParentId = List1[i]["ParentId"].ToString();
                        //首先找到对应的 NewId与Id在ParentId之间的关系
                        if(List1.Find(s => s["Id"].ToString() == tempParentId) != null)
                        {
                            tempNewId = List1.Find(s => s["Id"].ToString() == tempParentId)["NewId"].ToString();
                            sql = "update t_d_DrawCombo set ParentId=" + tempNewId + " where Id=" + List1[i]["NewId"].ToString();
                        }
                        else
                        {
                            continue;
                        }

                        
                    }
                    BaseDao.execute(sql);
                }
                string TreeObjStr = zTree.RebuildTree_DrawCombo(TCurr_ComboId);
                result.Add("TreeObjStr", TreeObjStr);


                result.Add("result", "OK");

                return Json(result);
            }
            catch (Exception e)
            {
                Console.Write(e.Message.ToString());
                result.Add("result", "error:" + e.Message.ToString().Replace("'", ""));
                return Json(result);
            }


        }





    }
}